<template>
  <div class="item-one" ref="itemOne">
    <div class="title">
      <span>资源管理</span>
      <div>
        <el-button type="primary" @click="addResource">新增资源</el-button>
        <el-button icon="el-icon-refresh"></el-button>
      </div>
    </div>
    <div class="container">
      <div class="screeningBox">
        <div class="leftBox">
          <div class="leftitem">
            <el-input
              class="merchants wid40"
              @keyup.enter.native="search"
              v-model.trim="conditions.name"
              placeholder="资源名称"></el-input>
          </div>
          <div class="leftitem">
            <el-select class="resType" v-model="conditions.resType" placeholder="资源类型" clearable>
              <el-option keys="1" label="ECS" value="1"></el-option>
              <el-option keys="2" label="RDS" value="2"></el-option>
              <el-option keys="2" label="Redis" value='3'></el-option>
              <el-option keys="2" label="DTS" value="4"></el-option>
              <el-option keys="2" label="域名" value="5"></el-option>
              <el-option keys="2" label="SSL证书" value="6"></el-option>
            </el-select>
          </div>
        </div>
        <div class="rightBox">
          <div class="rightitem">
            <el-input
              class="merchants wid40"
              @keyup.enter.native="search"
              v-model.trim="conditions.project"
              placeholder="所属项目"
            ></el-input>
          </div>
          <div class="rightitem">
            <el-button icon="el-icon-search" type="primary" @click="search">搜索</el-button>
            <el-button icon="el-icon-refresh" type="primary" @click="reset">重置</el-button>
          </div>
        </div>
      </div>

      <div class="tableBox">
        <el-table
          ref="multipleTable"
          :data="resourceArr"
          tooltip-effect="dark"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          stripe
          :header-cell-style="tableHeaderColor"
          v-loading="loading"
        >
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="name" align="center" label="名称" width="200"></el-table-column>
          <el-table-column prop="type" align="center" label="资源类型" width="100">
            <template slot-scope="scope">
              <span>{{typeName(scope.row.type)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="project" align="center" label="所属项目" width="100"></el-table-column>
          <el-table-column prop="brief" align="center" label="简述" width="350"></el-table-column>
          <el-table-column prop="expiredTime" align="center" label="过期时间" width="150"></el-table-column>
          <el-table-column prop="responser" align="center" label="负责人" width="300">
            <template slot-scope="scope">
              <span>{{getResponsers(scope.row.responser)}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="buyTime" align="center" label="采购时间" width="150"></el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="160">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="resourceUpdate(scope.row)"
              >编辑
              </el-button>
              <el-button type="text" size="small" @click="resourceDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            background
            @current-change="handleCurrentChange"
            @size-change="sizechange"
            :page-size="10"
            layout="total, sizes, prev, pager, next, jumper"
            :total="combined"
          ></el-pagination>
        </div>
      </div>
      <br>
      <br>
      <!-- 新增资源 -->
      <el-dialog v-dialogDrag title="新增资源" :visible.sync="eqma" width="50%" :close-on-click-modal="false">
        <el-form
          :model="resource"
          status-icon
          ref="resource"
          label-width="100px"
          class="demo-dynamic"
        >
          <el-form-item label="资源名称">
            <el-input type="text" v-model.trim="resource.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="资源类型">
            <el-select class="servicelevels" v-model="resource.type" placeholder="请选择">
              <el-option keys="1" label="ECS" :value="1"></el-option>
              <el-option keys="2" label="RDS" :value="2"></el-option>
              <el-option keys="2" label="Redis" :value="3"></el-option>
              <el-option keys="2" label="DTS" :value="4"></el-option>
              <el-option keys="2" label="域名" :value="5"></el-option>
              <el-option keys="2" label="SSL证书" :value="6"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属项目">
            <el-input type="text" v-model.trim="resource.project" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="简述">
            <el-input type="text" v-model.trim="resource.brief" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="采购时间">
            <div class="block">
              <el-date-picker
                v-model="resource.buyTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="过期时间">
            <div class="block">
              <el-date-picker
                v-model="resource.expiredTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间">
              </el-date-picker>
            </div>
          </el-form-item>
          <div class="demo-input-size">
            <el-form-item label="负责人">
              <el-input style="width:40%;margin-right:10px" placeholder="负责人名称" v-model="responserData.name"></el-input>
              <el-input style="width:40%;margin-right:10px" placeholder="负责人邮箱"
                        v-model="responserData.email"></el-input>
              <el-button type="primary" plain @click="addResponser()">添加</el-button>
            </el-form-item>
          </div>
          <el-table :data="responserArr" style="width: 100%">
            <el-table-column align=center prop="name" label="负责人名称"></el-table-column>
            <el-table-column align=center prop="email" label="负责人邮箱"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="120">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="delResponser(scope.row.name)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="eqma = false">取消</el-button>
          <el-button type="primary" @click="resourceSave">确定</el-button>
        </span>
      </el-dialog>
      <!-- 修改资源 -->
      <el-dialog v-dialogDrag title="修改资源" :visible.sync="amend" width="50%" :close-on-click-modal="false">
        <el-form
          :model="resourceUpdateParams"
          status-icon
          ref="resourceUpdateParams"
          label-width="110px"
          class="demo-dynamic"
        >
          <el-form-item label="资源名称">
            <el-input type="text" v-model="resourceUpdateParams.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="资源类型">
            <el-select class="servicelevels" v-model="resourceUpdateParams.type" placeholder="请选择">
              <el-option keys="1" label="ECS" :value="1"></el-option>
              <el-option keys="2" label="RDS" :value="2"></el-option>
              <el-option keys="2" label="Redis" :value="3"></el-option>
              <el-option keys="2" label="DTS" :value="4"></el-option>
              <el-option keys="2" label="域名" :value="5"></el-option>
              <el-option keys="2" label="SSL证书" :value="6"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="所属项目">
            <el-input type="text" v-model.trim="resourceUpdateParams.project" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="简述">
            <el-input type="text" v-model.trim="resourceUpdateParams.brief" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="采购时间">
            <div class="block">
              <el-date-picker
                v-model="resourceUpdateParams.buyTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item label="过期时间">
            <div class="block">
              <el-date-picker
                v-model="resourceUpdateParams.expiredTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择时间">
              </el-date-picker>
            </div>
          </el-form-item>
          <div class="demo-input-size">
            <el-form-item label="负责人">
              <el-input style="width:40%;margin-right:10px" placeholder="负责人名称" v-model="responserData.name"></el-input>
              <el-input style="width:40%;margin-right:10px" placeholder="负责人邮箱"
                        v-model="responserData.email"></el-input>
              <el-button type="primary" plain @click="addResponser()">添加</el-button>
            </el-form-item>
          </div>
          <el-table :data="responserArr" style="width: 100%">
            <el-table-column align=center prop="name" label="负责人名称"></el-table-column>
            <el-table-column align=center prop="email" label="负责人邮箱"></el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="120">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="delResponser(scope.row.name)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="amend = false">取消</el-button>
          <el-button type="primary" @click="resourceUpdateOk">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import {
    resourcePage,
    resourceSave,
    resourceUpdate,
    resourceDelete
  } from "@/api/api";

  export default {
    name: "item-one",
    data: function () {
      return {
        userinfo: {},
        token: {token: sessionStorage.getItem("token")},
        cur_page: 1,
        cur_size: 10,
        multipleSelection: [],
        amend: false,
        servicearr: [],
        resourceArr: [],
        combined: 10,
        pageCount: "",
        eqma: false,
        loading: true,
        responserArr: [],
        responserData: {},
        resource: {
          name: "",
          type: "",
          project: "",
          brief: "",
          buyTime: "",
          expiredTime: "",
          responser: ""
        },
        resourceUpdateParams: {
          name: "",
          type: "",
          project: "",
          brief: "",
          buyTime: "",
          expiredTime: "",
          responser: ""
        },
        conditions: {
          name: "",
          project: "",
          resType: "",
        }
      };
    },
    created() {
      this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));
      this.$store.dispatch("getNewNum", 6);
      this.resourceList();
    },
    methods: {
      //修改thead 背景色
      tableHeaderColor({row, column, rowIndex, columnIndex}) {
        if (rowIndex === 0) {
          return 'background-color: #F0F0F0;font-weight: 500;font-size:14px;color:#000;'
        }
      },
      // 刷新
      refresh() {
        this.$router.go({
        path: 0,
        query: {
          t: Date.now()
        }
      })
      },
      // 分页导航
      handleCurrentChange(val) {
        this.cur_page = val;
        this.resourceList();
        this.$nextTick(() => {
          document.querySelectorAll(".content")[0].scrollTop = "0";
        });
      },
      // 分页数量
      sizechange(val) {
        this.cur_size = val;
        this.resourceList();
        this.$nextTick(() => {
          document.querySelectorAll(".content")[0].scrollTop = "0";
        });
      },
      //多选框
      handleSelectionChange(val) {
        this.multipleSelection = val;
      },
      //  重置
      reset() {
        this.conditions = {
          resType: "",
          project: "",
          name: ""
        }
      },
      // 搜索
      search() {
        this.loading = true
        this.cur_page = 1
        this.resourceList();
      },
      // 打开添加资源Box
      addResource() {
        this.eqma = true;
        this.resource = {
          name: "",
          type: "",
          project: "",
          brief: "",
          buyTime: "",
          expiredTime: "",
          responser: ""
        }
        this.responserData = {}
        this.responserArr = []
      },
      // 添加负责人
      addResponser() {
        if (this.responserData.name && this.responserData.email) {
          this.responserArr.push(this.responserData)
          this.responserData = {}
        } else {
          this.$message.error('请确定负责人名称和邮箱');
        }
      },
      // 删除负责人
      delResponser(name) {
        const deleteIndex = this.responserArr.findIndex(item => {
          return item.name === name
        })
        this.responserArr.splice(deleteIndex, 1)
      },
      // 资源分页列表
      resourceList() {
        resourcePage({
          page: this.cur_page,
          size: this.cur_size,
          type: this.conditions.resType,
          project: this.conditions.project,
          name: this.conditions.name
        }).then(res => {
          if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
          } else {
            this.resourceArr = res.data.rows;
            this.combined = res.data.total;
            this.pageCount = res.data.totalPage;
            this.loading = false
          }
        });
      },
      // 添加资源
      resourceSave() {
        if (this.responserArr.length > 0) {
          this.resource.responser = encodeURI(JSON.stringify(this.responserArr));
        } else {
          this.resource.responser = ""
        }
        resourceSave(this.resource).then(res => {
          if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
          } else if (res.code == 200) {
            this.$message({
              message: "添加成功",
              type: "success"
            });
            this.eqma = false;
            this.resource = {payLogo: ""};
            this.resourceList();
          } else {
            this.$message.error(res.message);
          }
        });
      },
      // 删除资源
      resourceDelete(id) {
        this.$confirm("是否确定删除该资源？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            resourceDelete(id).then(res => {
              if (res.code == 405) {
                sessionStorage.removeItem("token");
                this.$router.push("/login");
              } else if (res.code == 200) {
                this.$message({
                  message: "已删除",
                  type: "success"
                });
                this.resourceList();
              } else {
                this.$message.error(res.message);
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消"
            });
          });
      },
      // 修改资源
      resourceUpdate(val) {
        this.amend = true;
        this.resourceUpdateParams.id = val.id;
        this.resourceUpdateParams.name = val.name;
        this.resourceUpdateParams.type = val.type;
        this.resourceUpdateParams.project = val.project;
        this.resourceUpdateParams.brief = val.brief;
        this.resourceUpdateParams.buyTime = val.buyTime;
        this.resourceUpdateParams.expiredTime = val.expiredTime;
        this.resourceUpdateParams.responser = val.responser;
        this.resourceUpdateParams.createTime = val.createTime;
        this.resourceUpdateParams.delFlag = val.delFlag;

        if (val.responser) {
          this.responserArr = JSON.parse(val.responser)
        } else {
          this.responserArr = []
        }
      },
      // 修改资源ok
      resourceUpdateOk() {
        if (this.responserArr.length > 0) {
          this.resourceUpdateParams.responser = encodeURI(JSON.stringify(this.responserArr));
        } else {
          this.resourceUpdateParams.responser = ""
        }
        resourceUpdate(this.resourceUpdateParams).then(res => {
          if (res.code == 405) {
            sessionStorage.removeItem("token");
            this.$router.push("/login");
          } else if (res.code == 200) {
            this.$message({
              message: "修改成功",
              type: "success"
            });
            this.amend = false;
            this.responserArr = [];
            this.responserData = {};
            this.resourceUpdateParams = {};
            this.resourceList();
          } else {
            this.$message.error(res.message);
          }
        });
      },
      // 应用类型
      typeName(val) {
        if (val == 1) {
          return "ECS"
        } else if (val == 2) {
          return "RDS"
        } else if (val == 3) {
          return "Redis"
        } else if (val == 4) {
          return "DTS"
        } else if (val == 5) {
          return "域名"
        } else if (val == 6) {
          return "SSL证书"
        }
      },
      getResponsers(val) {
        let responserNames = "";
        if (val) {
          let responserArr = JSON.parse(val);
          for (var i = 0; i < responserArr.length; i++) {
            responserNames += responserArr[i].name + ";"
          }
        }
        return responserNames;
      }
    }
  };
</script>
<style scoped lang='less'>
  .title {
    background: #fff;
    padding: 10px 10px;
    font-size: 18px;
    font-weight: 500;
    display: flex;
    justify-content: space-between;
  }

  .name {
    width: 25%;
  }

  .screeningBox {
    width: 100%;
    display: flex;
  }

  .leftBox,
  .rightBox {
    width: 50%;
    padding: 0 15px;
    box-sizing: border-box;
  }

  .leftBox > .leftitem {
    margin-bottom: 15px;
  }

  .rightBox > .rightitem {
    margin-bottom: 15px;
  }

  .merchants {
    width: 50%;
  }

  .tableBox {
    margin-top: 20px;
  }

  .resType {
    width: 30%;
  }

  .width20 {
    width: 20%;
  }

  .red {
    color: #f9607d;
  }

  .green {
    color: green;
  }

  .blue {
    color: #01aaef;
  }

  .stitle {
    padding: 5px 0;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    i {
      margin-left: 10px;
      margin-right: 5px;
    }
    .swarning {
      color: red;
    }
    .warning {
      color: #f9607d;
    }
  }

  .el-upload {
    height: 250px !important;
  }

  .el-autocomplete {
    width: 95%;
  }

  .resTypes {
    width: 95%;
  }

  .btnbox {
    width: 100%;
    text-align: center;
    margin-top: 20px;
    .btn {
      padding: 10px 25px;
    }
    .blue {
      background: rgb(95, 13, 226);
      color: #fff;
    }
  }
</style>